package cn.doitedu.basic.mr;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;
import java.util.ArrayList;

public class ReduceJoin {
    public static class JoinMapper extends Mapper<LongWritable, Text,Text, Text> {
        String name = "";

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            FileSplit inputSplit = (FileSplit) context.getInputSplit();
            name = inputSplit.getPath().getName();
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();

            String deviceId = "";
            String[] split = line.split(",");

            String v = value.toString();

            if (name.startsWith("a")) {
                deviceId = split[1];
                v = "a," + v;
            } else {
                deviceId = split[0];
                v = "b," + v;
            }

            context.write(new Text(deviceId),new Text(v));
        }
    }

    public static class JoinReducer extends Reducer<Text,Text,Text, NullWritable> {
        ArrayList<String> aDatas = new ArrayList<>();
        String bData = "";

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            for (Text value : values) {
                if(value.toString().startsWith("a")){
                    aDatas.add(value.toString());
                }else{
                    bData = value.toString();
                }
            }


            for (String aData : aDatas) {
                context.write(new Text(aData+","+bData),NullWritable.get());
            }
        }
    }
}
